/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.common.base.mvc;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaDataPermCheckService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.PlatformService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.service.rpc.SystemVariableRpcService;
import com.je.common.base.table.service.PCDataService;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @program: jecloud-common
 * @author: LIULJ
 * @create: 2021-03-12 09:25
 * @description: 抽象平台本地服务
 */
public abstract class AbstractPlatformController implements PlatformController {

    /**
     * 基础数据操作封装
     */
    @Autowired
    protected MetaService metaService;
    /**
     * 平台通用业务方法
     */
    @Autowired
    protected CommonService commonService;
    /**
     * 平台基础业务实现
     */
    @Autowired
    protected PlatformService manager;
    @Autowired
    protected PCDataService pcDataService;
    @Autowired
    protected SystemSettingRpcService systemSettingRpcService;
    @Autowired
    protected SystemVariableRpcService systemVariableRpcService;
    @Autowired
    protected MetaDataPermCheckService metaDataPermCheckService;

    @RequestMapping(value = "/move", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult move(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String id = getStringParameter(request, "id");
        String toId = getStringParameter(request, "toId");
        String place = getStringParameter(request, "place");
        if (StringUtil.isEmpty(id)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.transfer.source.notEmpty"));
        }
        if (StringUtil.isEmpty(toId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.transfer.target.notEmpty"));
        }
        if (StringUtil.isEmpty(place)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.transfer.target.placePosition"));
        }
        dynaBean.put("id", id);
        dynaBean.put("toId", toId);
        dynaBean.put("place", getStringParameter(request, "place"));
        DynaBean result = manager.move(dynaBean);
        return BaseRespResult.successResult(result, MessageUtils.getMessage("move.success"));
    }

    @Override
    @RequestMapping(value = "/load", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        Page page = manager.load(param, request);
        if (page == null) {
            return BaseRespResult.successResultPage(Lists.newArrayList(), 0L);
        }
        return BaseRespResult.successResultPage(page.getRecords(), (long) page.getTotal());
    }

    @Override
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(manager.doSave(param, request).getValues());
    }

    @Override
    @RequestMapping(value = "/doCopy", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doCopy(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(manager.doCopy(param, request).getValues());
    }

    @Override
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(manager.doUpdate(param, request).getValues());
    }

    @Override
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(String.format("%s 条记录被删除", manager.doRemove(param, request)));
    }

    @Override
    @RequestMapping(value = "/doDisable", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doDisable(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(String.format("%s 条记录被禁用", manager.doDisable(param, request)));
    }

    @Override
    @RequestMapping(value = "/doEnable", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doEnable(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(String.format("%s 条记录被启用", manager.doEnable(param, request)));
    }

    @Override
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        String funcType = param.getParameter("funcType");
        String updatesels = param.getParameter("updatesels");
        if (Strings.isNullOrEmpty(updatesels)) {
            updatesels = "1";
        }

        if (!Strings.isNullOrEmpty(funcType) && !funcType.equals("VIEW") || updatesels.equals("0")) {
            int i = manager.doUpdateList(param, request);
            return BaseRespResult.successResult(String.format("%s 条记录被更新", i));
        } else {
            List<DynaBean> list = manager.doUpdateListAndReturn(param, request);
            List<Object> returnList = new ArrayList<>();
            for (DynaBean dynaBean : list) {
                if (dynaBean == null || dynaBean.getValues() == null) {
                    break;
                }
                returnList.add(dynaBean.getValues());
            }
            Long count = Long.valueOf(list.size());
            return new BaseRespResult(returnList, String.format("%s 条记录被更新", count), "操作成功");
        }
    }

    @Override
    @RequestMapping(value = "/getInfoById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getInfoById(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean infoById = manager.getInfoById(param, request);
        if (infoById == null) {
            return BaseRespResult.successResult(new HashMap<>());
        }
        HashMap<String, Object> values = infoById.getValues();
        return BaseRespResult.successResult(values);
    }

    @Override
    @RequestMapping(value = "/checkFieldUnique", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult checkFieldUniquen(BaseMethodArgument param, HttpServletRequest request) {
        String result = manager.checkFieldUnique(param, request);
        if (StringUtil.isEmpty(result)) {
            return BaseRespResult.successResult("验证成功");
        } else {
            return BaseRespResult.errorResult(result);
        }
    }

    @RequestMapping(value = "/removeFileByFileKey", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Transactional(rollbackFor = Exception.class)
    public BaseRespResult removeFileByFileKey(BaseMethodArgument param, HttpServletRequest request) {
        String fileKeys = getStringParameter(request, "fileKeys");
        String tableCode = getStringParameter(request, "tableCode");
        String pkCode = getStringParameter(request, "pkCode");
        String pkValue = getStringParameter(request, "pkValue");
        String fileField = getStringParameter(request, "fileField");
        if (StringUtils.isBlank(fileKeys)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("fileKeys.notEmpty"));
        }
        //业务服务删除对应字段的，文件信息
        if (!Strings.isNullOrEmpty(tableCode) && !Strings.isNullOrEmpty(pkCode)
                && !Strings.isNullOrEmpty(pkValue) && !Strings.isNullOrEmpty(fileField)) {

            DynaBean dynaBean = metaService.selectOne(tableCode, ConditionsWrapper.builder().table(tableCode).eq(pkCode, pkValue));
            if (dynaBean != null) {
                //获取附件字段最新值
                //去除文件key对象
                String fileContent = dynaBean.getStr(fileField);
                JSONArray newJsonArray = new JSONArray();
                JSONArray jsonArray = JSONArray.parseArray(fileContent);
                if (null != jsonArray) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        if (!fileKeys.contains(jsonObject.get("fileKey").toString())) {
                            newJsonArray.add(jsonObject);
                        }
                    }

                    String updateSql = fileField + " = '" + newJsonArray + "' where " + pkCode + " = '" + pkValue + "'";
                    metaService.executeSql(String.format("UPDATE %s SET %s", tableCode, updateSql));
                }
            }
        }
        String userId = SecurityUserHolder.getCurrentAccountRealUser().getId();
        commonService.deleteByFileKeys(Arrays.asList(fileKeys.split(",")), userId);
        return BaseRespResult.successResult("成功");
    }

    @RequestMapping(value = "/statistics", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult statistics(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(manager.statistics(param, request));
    }

    @Override
    @RequestMapping(value = "/batchModifyListData", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult batchModifyListData(BaseMethodArgument param, HttpServletRequest request) {
        int i = manager.batchModifyListData(param, request);
        return BaseRespResult.successResult("批量修改成功！");
    }

}
